package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserActivateService;
import com.heima.user.util.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ApUserActivateServiceImpl implements ApUserActivateService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult sendCode(String email) {
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getEmail, email));
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(uuid,apUser.getId().toString(),2, TimeUnit.MINUTES);
        MailUtils.sendMail(email,"<a href = \"http://localhost:6001/user/api/v1/activate/in?code="+uuid+"\">点击激活记得账户</a>","激活账户");
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult activate(String code) {
        Integer apUserId = Integer.valueOf(redisTemplate.opsForValue().get(code));
        ApUser apUser = apUserMapper.selectById(apUserId);
        apUser.setStatus(false);
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult();
    }
}
